package com.augurit.gzcgwsp.mail.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jbpm.api.history.HistoryProcessInstance;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.mail.SendMail;
import com.augurit.gzcgwsp.mail.dao.MailDao;
import com.augurit.gzcgwsp.mail.entity.Mail;
import com.augurit.gzcgwsp.mail.service.ISendMailService;
import com.augurit.gzcgwsp.printDoc.entity.YwPrintDoc;
import com.augurit.gzcgwsp.ywcmn.entity.YwComQyxx;
import com.augurit.wf.common.form.TraceRecord;
import com.augurit.wf.common.service.IWfService;
@Service
@Transactional
/**
 * 邮件发送service
 */
public class SendMailServiceImpl implements ISendMailService{
	private static final Logger logger=Logger.getLogger( SendMailServiceImpl.class);
		@Autowired
		private MailDao mailDao;
		@Autowired
		private IWfService wfService;
		@Autowired
		private SendMail sendMail;
		/*
		 * 发送邮件
		 * @see com.augurit.gzcgwsp.ywcmn.service.ISendMailService#send(java.lang.String, java.lang.String, java.lang.String)
		 */
		public void send() {
			List<Mail> list=getMails();
			logger.info("需要发送的邮件数------->"+list.size());
			int count=0;
			for(Mail mail:list){
				if(this.checkEmail(mail.getAccount())){
					boolean flag=sendMail.sendMail(mail.getTitle(), mail.getAccount(), mail.getContent());
					if(flag){
						mail.setSendTime(DateUtilsEX.dateFormate(new Date(), "yyyy-MM-dd HH:mm:ss"));
						mail.setSts("1");
						mailDao.save(mail);
						count++;
					}else{
						mail.setSts("3");
						mailDao.save(mail);
						logger.info("邮件发送失败");
						count++;
					}
				}
			}
			logger.info("邮件一共发送了"+count+"条记录");
		}


		
		
		/*
		 * 往邮件表插入数据
		 *
		 */
		public void insertMail() {
			List<Object[]> list=getApproveInfo();
			Mail mail=null;
			int count=0;
			for(Object[] obj:list){
				String companyName=(String) obj[0];//企业信息
				String acceptNo=(String) obj[1];//受理编号
				String tempCode=(String) obj[2];//业务编码
				String tempName=(String)obj[3];//业务名称
				String procInstId=(String)obj[4];//流程实例id
				String ywid=(String) obj[5];
				String acceptDate=DateUtilsEX.dateFormate((Date) obj[6], "yyyy年MM月dd日");
				String result=getResult(tempCode,ywid);//审批结果
				List<Mail> mails=getMailByAcceptNo(acceptNo);//是否存在了数据
				
				if(mails.size()<=0){
					mail=new Mail();
					mail.setAccep_no(acceptNo);
					String email=getCompanyMailByName(companyName,tempCode);
					if(StringUtils.isNotBlank(email)){
						mail.setAccount(email);
						mail.setSts("2");
						String content=buildMailContent(companyName,tempName,result,procInstId,acceptNo,acceptDate);
						content=content.replace("null", "");
						mail.setContent(content);
						mail.setReceiveTime(DateUtilsEX.dateFormate(new Date(), "yyyy-MM-dd HH:mm:ss"));
						mail.setTitle("广州城市管理委员会 "+tempName+" 审批结果");
						try {
							mailDao.save(mail);
						} catch (Exception e) {
							logger.info("插入邮件错误"+e);
						}
						count++;
					}
				}
				
			}
			logger.info("一共插入了"+count+"条记录");
		}

		/**
		 * 获取是否同意的结果
		 * @param tempCode
		 * @param ywid
		 * @return 
		 * @date 2012-4-2
		 */
		private String getResult(String tempCode, String ywid) {
			String result="准予许可";
			String hql="from YwPrintDoc where templateCode='"+tempCode+"' and ywId="+ywid+" and fileCode in ('byxkjds','zyxzxkjds','bzcltzs')";
			List list=this.mailDao.find(hql);
			if(list!=null &&list.size()>0){
				YwPrintDoc doc=(YwPrintDoc) list.get(0);
				if("byxkjds".equals(doc.getFileCode())){
					result="不予许可";
				}else if("bzcltzs".equals(doc.getFileCode())){
					result="一次性告知";
				}
				
			}
			return result;
			
		}




		/**
		 * 构造邮件内容
		 * @param companyName
		 * @param tempName
		 * @param result
		 * @return
		 */
		private String buildMailContent(String companyName,String tempName, String result,String procInstId,String acceptNo,String acceptDate) {
			StringBuffer sb=new StringBuffer("<html><div style='font:normal 1em arial; margin-top:10px'>");
			 sb.append("<strong>");
			 sb.append(companyName+"：");
			 sb.append("</strong><br  /><p>&nbsp;&nbsp;&nbsp;&nbsp;你好，");
			 sb.append("你公司"+acceptDate+"提交的");
			 sb.append(tempName);
			 sb.append("审批已经完成，受理编号"+acceptNo);
			 sb.append("审批结果");
			 sb.append(result+"<br/>");
			// String opion=getOpinionsByProInstId(procInstId);
			 //sb.append(opion);
			 sb.append("&nbsp;&nbsp;&nbsp;&nbsp;如有疑问，请与相关业务处联系");
			 sb.append("<br  /></p>");
			 sb.append("<p style='text-align:right;'>  广州市城市管理委员会</p><br/>");
			 sb.append("</html>");
			return sb.toString();
		}

		/**
		 * 获取所有的审批意见
		 * @param proInstId
		 * @return
		 */
		private String getOpinionsByProInstId(String procInstId){
			String opion="";
			if(StringUtils.isNotBlank(procInstId)){
				 List<TraceRecord> list = wfService.getTraceInfo(procInstId);
		 	    for(TraceRecord record:list){
		 	    	if(record.getActivityName().indexOf("gz")<0){//电子盖章的意见
		 	    		opion+="&nbsp;&nbsp;&nbsp;&nbsp;"+record.getHandleComments()+"&nbsp;&nbsp;"
		 	    		   +record.getAssignee()+"&nbsp;&nbsp;"+record.getHandleCommentsTime()+"<br/>";
		 	    	}
		 	    }
			}
			return opion;
		}
		
		/**
		 * 根据企业名称和编号查询企业邮箱
		 * @param companyName 企业邮箱
		 * @param tempCode 业务编码
		 * @return
		 */
		private String getCompanyMailByName(String companyName, String tempCode) {
			String hql=" select t.email from "+YwComQyxx.class.getName()+
					   " t where t.sqdw='"+companyName+"' and t.templateCode='"+tempCode+"'";
			List<Object> list=mailDao.find(hql);
			String mailAccount="";
			if(list.size()>0){
				mailAccount=(String) list.get(0);
			}
			return mailAccount;
		}
	
		/**
		 * 检查邮箱格式是否正确
		 * @param email email
		 * @return
		 */
		public   boolean checkEmail(String email) {  
			String match="[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+";
			if (!email.matches(match)) 
				return false; 
		    else
		    	return true;
		}

		/**
		 * 获取所有没发送的短信
		 * @return
		 */
		 public List<Mail> getMails(){
			 String hql="from "+Mail.class.getName()+" where sts!='1'";
			 return mailDao.find(hql);
		 }
	 
		/**
		 * 查询此审批业务邮件是否存在
		 * @return
		 */
		 private List<Mail> getMailByAcceptNo(String acceptNo){
			 String hql="from "+Mail.class.getName()+" where accep_no='"+acceptNo+"'";
			 return mailDao.find(hql);
		 }
		 
	 
	 /**
	  * 获取审批完成的信息(主要查询工作流的企业名称,申请编号,业务编码构造)
	  * @return
	  */
	private List<Object[]> getApproveInfo(){
	    SimpleDateFormat dateformat =new SimpleDateFormat("yyyy-MM-dd");
	    Calendar now =java.util.Calendar.getInstance();
	    now.add(Calendar.DATE,-1);//前一天的时间，原来是查询两小时前的数据
	    Date date =now.getTime();
	    String twoHourAgo =dateformat.format(date);
		StringBuffer sb=new StringBuffer();
		Map<String, Object> values = new HashMap();
		sb.append("select distinct inst.busMemo1,inst.busMemo3,temp.templateCode,temp.templateName,inst.procInstId");
		sb.append(" ,inst.masterEntityKey,inst.busDate2 from Jbpm4HistProcinst as proc,WfBusInstance inst,Jbpm4HistTask as task, WfBusTemplate temp");
		sb.append(" where  proc.procInstId = inst.procInstId");
		sb.append(" and task.procInstId = proc.procInstId and task.state='"+Task.STATE_COMPLETED+"'");
		sb.append(" and proc.state='"+HistoryProcessInstance.STATE_ENDED+"'");
		sb.append(" and  inst.templateId = temp.id ");
		sb.append(" and proc.end>= :busDate2");
		values.put("busDate2",date);
		List<Object[]> list=mailDao.find(sb.toString(),values);
		logger.info("查询出一天内结案的数------->"+list.size());
		return list;
	}
	
}
